<?php

/**
 * This is the model class for table "tbl_category".
 *
 * The followings are the available columns in table 'tbl_category':
 * @property integer $id
 * @property string $title
 * @property string $description
 * @property string $image
 * @property integer $parent_id
 * @property integer $is_visible
 * @property string $created_at
 *
 * The followings are the available model relations:
 * @property Product[] $products
 */
class Category extends CActiveRecord
{
    private static $_items=array();
    /**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return 'tbl_category';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('title', 'required', 'message'=>'{attribute} не может быть пустым.'),
            array('title', 'unique', 'className'=>'Category', 'message'=>'Категория с таким названием уже существует'),
			array('parent_id, is_visible', 'numerical', 'integerOnly'=>true),
			array('title', 'length', 'max'=>256),
			array('image', 'length', 'max'=>1024),
			array('created_at', 'safe'),
			// The following rule is used by search().
			// @todo Please remove those attributes that should not be searched.
			array('id, title, description, image, parent_id, is_visible, created_at', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
            'parent'=>array(self::BELONGS_TO, 'Category', 'parent_id'),
			'products' => array(self::HAS_MANY, 'Product', 'category_id'),
            'categories' => array(self::HAS_MANY, 'Category', 'parent_id', 'condition'=>'is_visible=:visible', 'params'=>array(':visible'=>true), 'order'=>'title ASC'),
            'productsCount'=>array(self::STAT, 'Product', 'category_id')

		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id' => 'ID',
			'title' => 'Название категории',
			'description' => 'Описание категории (реклама)',
			'image' => 'Изображение',
			'parent_id' => 'Родительская категория',
			'is_visible' => 'Отображать категорию',
			'created_at' => 'Дата создания',
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 *
	 * Typical usecase:
	 * - Initialize the model fields with values from filter form.
	 * - Execute this method to get CActiveDataProvider instance which will filter
	 * models according to data in model fields.
	 * - Pass data provider to CGridView, CListView or any similar widget.
	 *
	 * @return CActiveDataProvider the data provider that can return the models
	 * based on the search/filter conditions.
	 */
	public function search()
	{
		// @todo Please modify the following code to remove attributes that should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('id',$this->id);
		$criteria->compare('title',$this->title,true);
		$criteria->compare('description',$this->description,true);
		$criteria->compare('image',$this->image,true);
		$criteria->compare('parent_id',$this->parent_id);
		$criteria->compare('is_visible',$this->is_visible);
		$criteria->compare('created_at',$this->created_at,true);

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria
		));
	}

	/**
	 * Returns the static model of the specified AR class.
	 * Please note that you should have this exact method in all your CActiveRecord descendants!
	 * @param string $className active record class name.
	 * @return Category the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

    //формирование массива категорий, в которые нельзя добавить товар
    public function getDisabledCategories(){
        $disabledArray = array();
        foreach (self::model()->findAll() as $category){
            if ($category->categories){
                $disabledArray[$category->id] = array('disabled'=>'disabled');
            }
        }
        return $disabledArray;
    }
    //конец формирования массива категорий, в которые нельзя добавить товар
    
    //формирование массива категорий, в которые нельзя добавить подкатегорию
    public function getDisabledSubCategories(){
        $disabledArray = array();
        foreach (self::model()->findAll() as $category){
            if ($category->products){
                $disabledArray[$category->id] = array('disabled'=>'disabled');
            }
        }
        return $disabledArray;
    }
    //конец формирования массива категорий, в которые нельзя добавить подкатегорию

    //формирование древовидного списка категорий
    public function buildSubTree($model, $url='update'){
        $tree = "<ul class='second'>";
        foreach ($model->categories as $category) {
            $tree .= "<li> <a href=".Yii::app()->controller->createUrl($url, array("id"=>$category->id)).">". $category->title."</a>";
            if ($category->categories) {
                $tree .= $this->buildSubTree($category, $url);
            };
        }
        $tree .= '</ul>';

        return $tree;
    }

    public function buildTree($url='update'){
        $tree = '';
        foreach (self::model()->findAll(array(
            'condition'=>'parent_id=:id AND is_visible=:visible',
            'params'=>array(':id'=>0, ':visible'=>true),
            'order'=>'title ASC'
        )) as $model){
            $tree .= "<ul class='first'>";
            $tree .= "<li> <a href=".Yii::app()->controller->createUrl($url, array("id"=>$model->id)).">". $model->title."</a>";
            $tree .= $this->buildSubTree($model, $url);
            $tree .= "</ul>";
        }

        return $tree;
    }
    //конец формирования древовидного списка категорий

    //построение многоуровневого аккордеона

    public function buildSubAccordion($model, $url='update', $currentModel=null){

        $tree = '<div class="panel-group" id="accordion'.$model->id.'">';
        foreach ($model->categories as $category) {
            $in = in_array($category->id, $this->buildParentsAccordion(self::model()->findByPk($currentModel))) ? ' in' : '';
            if ($category->categories) {
                $tree .= '<div class="panel panel-default beebee-accordion">
                          <div class="panel-heading">
                              <h4 class="panel-title">
                                  <a data-toggle="collapse" data-parent="#accordion'.$model->id.'" href="#collapse' . $category->id . '">';
                $tree .= $category->title;
                $tree .= '            </a>
                              </h4>
                          </div>
                          <div id="collapse' . $category->id . '" class="panel-collapse collapse' . $in . '">
                            <div class="panel-body">';
                $tree .= $this->buildSubAccordion($category, $url, $currentModel);
                $tree .= '      </div>
                          </div>
                     </div>';
            } else {
                $style = $currentModel == $category->id ? 'style = "color: #FF0;"' : '';
                $tree .= '<div class="panel panel-default">
                          <div class="panel-heading">
                              <h4 class="panel-title"'.$style.'>
                <a href="' . Yii::app()->createUrl($url, array("id"=>$category->id)) . '">';
                $tree .= $category->title;
                $tree .= '        </a>
                              </h4>
                          </div>';
                $tree .= '   </div>';
            };
        }
        $tree .= '</div>';

        return $tree;
    }

    public function buildAccordion($url='update', $currentModel=null){
        $tree = '';
        $tree .= '<div class="panel-group" id="accordion">';
        foreach (self::model()->findAll(array(
            'condition'=>'parent_id=:id AND is_visible=:visible',
            'params'=>array(':id'=>0, ':visible'=>true),
            'order'=>'title ASC'
        )) as $model){
            $in = in_array($model->id, $this->buildParentsAccordion(self::model()->findByPk($currentModel))) ? ' in' : '';
            if ($model->categories) {
            $tree .= '<div class="panel panel-default beebee-accordion">

                          <div class="panel-heading">
                          <a data-toggle="collapse" data-parent="#accordion" href="#collapse' . $model->id . '">
                              <h4 class="panel-title">
                                  ';
            $tree .= $model->title;
            $tree .= '
                              </h4>
                              </a>
                          </div>
                          <div id="collapse' . $model->id . '" class="panel-collapse collapse'.$in.'">
                            <div class="panel-body">';
            $tree .= $this->buildSubAccordion($model, $url, $currentModel);;
            $tree .= '      </div>
                          </div>
                     </div>';
            } else {
                $style = $currentModel == $model->id ? 'style = "color: #FF0;"' : '';
                $tree .= '<div class="panel panel-default">

                          <div class="panel-heading">
                          <a href="' . Yii::app()->createUrl($url, array("id"=>$model->id)) . '">
                              <h4 class="panel-title"'.$style.'>
                                  ';
                $tree .= $model->title;
                $tree .= '
                              </h4>
                              </a>
                          </div>
                          </div>';
            }

        }
        $tree .= '</div>';
        return $tree;
    }

    //конец построения многоуровневого аккордеона
    
    //формирование листа для выпадающего списка
    public function buildSubArray($model, $prefix='') {
        if (!isset($subArray)) $subArray = array();
		$prefix .= ' • • ';
		foreach ($model->categories as $category){
			$subArray[$category->id] = $prefix . $category->title;
			if ($category->categories) {								
				$subArray = $subArray + $this->buildSubArray($category, $prefix);
			}
		}
		return $subArray;
	}
	
	public function buildDropDownList(){
		$list = array();
        foreach (self::model()->findAll(array(
            'condition'=>'parent_id=:id',
            'params'=>array(':id'=>0),
            'order'=>'title ASC'
        )) as $model){
                $list[$model->id] = $model->title;
            $list = $list + $this->buildSubArray($model);
        }

        return $list;
	}
	//конец формирования листа для выпадающего списка

    //формирование массива родителей для хлебных крошек
    public function buildParentsArray($model, $url='/subkatalog'){
        if (!isset($parents_array)) $parents_array = array();
        if ($model->parent){
        $parents_array[$model->parent->title]=Yii::app()->createUrl($url, array('id'=>$model->parent->id));
        if ($model->parent->parent_id > 0){
            $parents_array = $this->buildParentsArray($model->parent) + $parents_array;
        }
        }
        return $parents_array;
    }
    //конец формирования массива родителей  для хлебных крошек

    //формирование массива родителей для аккордеона
    public function buildParentsAccordion($model){
        if (!isset($parents_array)) $parents_array = array();
        if (isset($model->parent)){
            $parents_array[]=$model->parent->id;
            if ($model->parent->parent_id > 0){
                $parents_array = array_merge($this->buildParentsAccordion($model->parent), $parents_array);
            }
        }
        return $parents_array;
    }
    //конец формирования массива родителей для аккордеона

}
